/*********************************************************************************
 *      Copyright:  (C) 2022 Li Yanting<liyanting2@163.com>
 *                  All rights reserved.
 *
 *       Filename:  client_socket.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(04/19/2022)
 *         Author:  Li Yanting <liyanting2@163.com>
 *      ChangeLog:  1, Release initial version on "04/19/2022 12:28:49 PM"
 *                 
 ********************************************************************************/

#include "client_socket.h"

/*********************************************************************************
 *      function name:  socket_init_client
 *        Description:  create sockfd.
 *       return value:  On error, -1 is returned. On success, sockfd is returned.
 *          parameter:  serv_ip; serv_port.
 ********************************************************************************/
int socket_connect_client(char *serv_ip, int serv_port)
{
    int                   sockfd = -1;
    struct sockaddr_in    servaddr;
    socklen_t             len;
    int                   rv = -1;
    
    if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
    {
        dbg_printf("socket failure: %s\n", strerror(errno));
        return -1;
    }
    dbg_printf("fd: %d\n",  sockfd);

    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(serv_port);
    inet_aton(serv_ip, &servaddr.sin_addr);
    if( (rv = connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr))) < 0 )
    {
        dbg_printf("connect to server failure: %s\n", strerror(errno));
        close(sockfd);
        return -2;
    }
    dbg_printf("create sockfd and connect to server successfully\n");

    return sockfd;
}

/*********************************************************************************
 *      function name:  get_socket_state
 *        Description:  get socket state.
 *       return value:  On error, -1 is returned. On success, 0 is returned.
 *          parameter:  sockfd.
 ********************************************************************************/
int get_socket_state(int sockfd)
{
    struct tcp_info    info;
    int                len = sizeof(info);
    getsockopt(sockfd, IPPROTO_TCP, TCP_INFO, &info, (socklen_t*)&len);
    if(info.tcpi_state == TCP_ESTABLISHED)
    {
        return 0;
    }
    else
    {
        return -1;
    }
}

